<?php

namespace App\Modules\Finance\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

/**
 * Class Bill 账单
 * @package App\Modules\Finance\Models
 */
class Bill extends Model
{
	protected $table = 'bills';
	//recharge_amount:充值金额
    protected $fillable = ['distribution_channel_id','distribution_channel_name', 'date','recharge_amount', 'tallage', 'settlement_price','rate'];

    /**
     * 根据渠道ID，时间，获取列表
     * @param $distribution_channel_id
     * @param $distribution_channel_name
     * @param string $start_date
     * @param string $end_date
     * @param bool $is_all
     * @return mixed
     */
    static function getListByDistributionChannel($distribution_channel_id, $distribution_channel_name, $start_date='',$end_date='', $is_all=false)
    {
        $search_object = self::orderBy('date','desc');

        if($distribution_channel_id) {
            $search_object->where('distribution_channel_id', $distribution_channel_id);
        }
        if($distribution_channel_name) {
            $search_object->where('distribution_channel_name', $distribution_channel_name);
        }
        if($start_date) $search_object->where('date','>=',$start_date);
        if($end_date) $search_object->where('date','<=',$end_date);
        if($is_all)
        {
            return $search_object->get();
        }else{
            return $search_object->paginate();
        }
    }

    /**
     * 获取结算列表
     * @param $params[]
     *                  channel_id:渠道ID 可选
     *                  channel_name:渠道名称 可选
     *                  search_name: 搜索名称
     *                  start_date:开始时间 可选
     *                  end_date:结束时间 可选
     * * @param bool $is_all
     * @return mixed
     */
    public static function getBillList($params = [], $is_all=false) {
        $search_object = self::orderBy('date','desc')
            ->where('recharge_amount', '>', 0);

        if(isset($params['channel_id']) && $params['channel_id']) $search_object->where('distribution_channel_id', $params['channel_id']);
        if(isset($params['channel_name']) && $params['channel_name']) $search_object->where('distribution_channel_name','like', "%".$params['channel_name']."%");

        if(isset($params['search_name']) && $params['search_name']) {
            $search_object->where(function ($query) use($params) {
                $query->where('distribution_channel_name','like', "%".$params['search_name']."%");
            });
        }

        if(isset($params['start_date']) && $params['start_date']) $search_object->where('date','>=', $params['start_date']);
        if(isset($params['end_date']) && $params['end_date']) $search_object->where('date','<=', $params['end_date']);

        if($is_all)
        {
            return $search_object->get();
        }else{
            return $search_object->paginate();
        }
    }

    public static function getTotalInfo($params = [])
    {
        $search_object = self::orderBy('date', 'desc')
            ->where('recharge_amount', '>', 0);

        if (isset($params['channel_id']) && $params['channel_id']) $search_object->where('distribution_channel_id', $params['channel_id']);
        if (isset($params['channel_name']) && $params['channel_name']) $search_object->where('distribution_channel_name', 'like', "%" . $params['channel_name'] . "%");

        if (isset($params['search_name']) && $params['search_name']) {
            $search_object->where(function ($query) use ($params) {
                $query->where('distribution_channel_name', 'like', "%" . $params['search_name'] . "%");
            });
        }

        if (isset($params['start_date']) && $params['start_date']) $search_object->where('date', '>=', $params['start_date']);
        if (isset($params['end_date']) && $params['end_date']) $search_object->where('date', '<=', $params['end_date']);

        $search_object->select(DB::raw('sum(recharge_amount) as total_recharge_amount,sum(settlement_price) as total_settlement_price'));
        return $search_object->first();
    }


    /**
     * 获取当前渠道当前结算比例
     * @param $channelId
     * @return float
     */
    public static function getRate($channelId) {
        $rate = 0.0;
        $startMonth = date('Y-m-01', strtotime(date("Y-m-d")));
        $endMonth = date('Y-m-d', strtotime("$startMonth +1 month -1 day"));
        $rechargeAmountCount = Bill::where('distribution_channel_id',$channelId)
            ->where('date', '<=', $endMonth)
            ->where('date', '>=', $startMonth)
            ->sum('recharge_amount');

        $commissionRates = CommissionRate::where('distribution_channel_id', $channelId)
            ->orderBy('begin_amount', 'asc')
            ->get();
        foreach ($commissionRates as $commissionRate) {
            if($rechargeAmountCount >=  $commissionRate['begin_amount']) {
                //结束金额存在，并且结算金额小于结束金额，结束
                if(!empty($commissionRate['end_amount']) && is_numeric($commissionRate['end_amount']) && $commissionRate['end_amount'] > 0 && $rechargeAmountCount < $commissionRate['end_amount']) {
                    $rate = $commissionRate['rate'];
                    break;
                }
                $rate = $commissionRate['rate'];
            }
        }

        return $rate;
    }

    /**
     * 创建结算单
     * @param $channelId
     * @param $channelName
     * @param $rechargeAmount
     */
    public static function makeBill($channelId, $channelName, $rechargeAmount) {
        $rate = Bill::getRate($channelId);
        $dataBill['distribution_channel_id'] = $channelId;
        $dataBill['distribution_channel_name'] = $channelName;
        $dataBill['date'] = date("Y-m-d", strtotime(date("Y-m-d")." -1 day"));
        $dataBill['recharge_amount'] = (float)$rechargeAmount;
        $dataBill['settlement_price'] = (float)$rechargeAmount * $rate;
        $dataBill['rate'] = $rate;
//        $dataBill['tallage'] = ((float)$rechargeAmount) - ((float)$rechargeAmount * $rate);
        //TODO 扣税金额为 0
        $dataBill['tallage'] = 0;

        DB::beginTransaction();
        try{
            Bill::create($dataBill);
            //更新创建提现信息
            $dataFinancialStatDB = FinancialStat::where('distribution_channel_id', $channelId)->first();
            if(empty($dataFinancialStatDB)) {
                $dataFinancialStat['distribution_channel_id'] = $channelId;
                $dataFinancialStat['accumulative_withdrawal_amount'] = 0;
                $dataFinancialStat['enable_withdrawal_amount'] = $dataBill['settlement_price'];
                $dataFinancialStat['latest_withdrawal_amount'] = 0;
                $dataFinancialStat['withdraw_pending_amount'] = 0;
                $dataFinancialStat['commission_rate'] = $rate;

                FinancialStat::create($dataFinancialStat);
            } else {
                $dataFinancialStatDB['enable_withdrawal_amount'] = (float)$dataFinancialStatDB['enable_withdrawal_amount'] + (float)$dataBill['settlement_price'];
                $dataFinancialStatDB['commission_rate'] = $rate;

                $dataFinancialStatDB->save();
            }

            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
        }
    }
}
 